/**
 * 管理员页面
 */

import { Avatar, Button, Col, Flex, Form, Input, Modal, Row, Space, Table } from "antd";
import { BaseContiner, FlexContainer, LeftContainer, RightContainer, TableContainer, TableHeader } from "../../../csscomponents/base";
import { useCallback, useRef, useState } from "react";
import { ISys, ISysSearchParams, useDeletedSysById, useGetSysBySearch } from "../../../service/syscontroller";
import { ErrorBox } from "../../../components/error-box";
import {
    PlusOutlined
} from '@ant-design/icons';
import { useForm } from "antd/es/form/Form";
import SysForm from "./sys-form";
import { IFormRef, IRoleRestFillRefHandler } from "../../../types";
import UnitTree from "../../../components/unit-tree";
import { userState } from "../../../stores/user";
import { useRecoilState } from "recoil";
const SysPage = () => {
    const [sys] = useRecoilState(userState);
    const unitTreeRef = useRef<IRoleRestFillRefHandler>();
    /**
     * 默认查询参数
     */
    const defaultQueryParams = {
        sysName: "",
        unitId: sys.userInfo.unitId || '',
        page: 1,
        limit: 10
    }
    /**
     * 搜索参数
     */
    const [queryParams, setQueryParams] = useState<ISysSearchParams>(defaultQueryParams)
    const [queryForm] = useForm();
    const sysFormRef = useRef<IFormRef>();
    const [openSysDrawStatus, setOpenDrawStatus] = useState<boolean>(false);
    // 当前修改的管理员
    const [updateSys, setUpdateSys] = useState<ISys>();
    /**
     * 搜索管理员列表Handler
     * @param values 搜索参数
     */
    const onFinish = (values: { sysName: string }) => {
        setQueryParams({ ...queryParams, sysName: values.sysName })
    }
    /**
     * 重置搜索
     */
    const resetQueryParams = () => {
        setQueryParams(defaultQueryParams);
        queryForm.resetFields();
    }
    /**单位选中回调 */
    const getCheckUnitCallback = useCallback((unitId: string, unitName: string) => {
        if (unitId && unitId !== queryParams.unitId) {
            setQueryParams({ ...queryParams, unitId: unitId });
        }
    }, [queryParams])

    /**
     * 删除管理员
     * @param sysId 管理员ID
     */
    const removeSysHandler = (sysId: string) => {
        Modal.confirm({
            title: '⚠️警告',
            content: '你确认执行改操作吗?',
            okText: '确认',
            cancelText: '取消',
            onOk: async () => {
                await deleteSysMutation({ sysId });
                refetch();
            },
        });
    }

    const columns = [
        {
            title: '名称',
            dataIndex: 'sysName',
            key: 'sysName',
        },
        {
            title: '昵称',
            dataIndex: 'sysNickName',
            key: 'sysNickName',
        },
        {
            title: '角色',
            dataIndex: 'sysRoleName',
            key: 'sysRoleName',
        },
        {
            title: '手机号码',
            dataIndex: 'phone',
            key: 'phone',
        },
        {
            title: '头像',
            dataIndex: 'sysAvater',
            key: 'sysAvater',
            render(value: string) {
                return <Avatar shape="square" size={64} src={value} />;
            },
        },
        {
            title: '创建时间',
            dataIndex: 'createTime',
            key: 'createTime',
        },
        {
            title: '更新时间',
            dataIndex: 'updateTime',
            key: 'updateTime',
        },
        {
            title: '更多操作',
            render(project: ISys) {
                return (
                    project.sysId === "1" ? null : <div>
                        <Button
                            style={{ marginRight: '1.2rem' }}
                            onClick={() => {
                                setUpdateSys(project);
                                setOpenDrawStatus(true);
                            }}
                        >
                            修改
                        </Button>
                        <Button loading={DIsLoading} danger onClick={() => removeSysHandler(project.sysId)}>
                            删除
                        </Button>
                    </div>
                );
            },
        },
    ];

    /**
     * !获取管理员列表Hook
     */
    const { isLoading, isError, data: dataSource, error, refetch } = useGetSysBySearch(queryParams);

    /**
     * !删除角色接口Hook
     */
    const { mutateAsync: deleteSysMutation, isLoading: DIsLoading } = useDeletedSysById();
    /**
    * 分页配置
    */
    const paginationProps = {
        total: dataSource?.count,
        pageSize: queryParams.limit,
        current: queryParams.page,
        showTotal: (count: number) => {
            return `共 ${count} 条`;
        },
        onChange: (pageNum: number) => {
            setQueryParams({ ...queryParams, page: pageNum });
        },
    };

    /**
     *控制侧边栏
     */
    const onCloseHandler = useCallback((status: boolean) => {
        setOpenDrawStatus(status)
    }, [])

    return <FlexContainer>
        <LeftContainer>
            <UnitTree getCheckUnit={getCheckUnitCallback} onRef={unitTreeRef} />
        </LeftContainer>
        <RightContainer>
            <BaseContiner>
                <TableHeader>
                    <Form
                        form={queryForm}
                        style={{ width: '100%' }}
                        name="sys_search_form"
                        onFinish={onFinish}
                        autoComplete="off"
                    >
                        <Row gutter={16}>
                            <Col span={10}>
                                <Form.Item label="名称" name="sysName" >
                                    <Input />
                                </Form.Item>
                            </Col>
                            <Col span={10}>
                                <Form.Item >
                                    <Space>
                                        <Button type="primary" htmlType="submit">
                                            搜索
                                        </Button>
                                        <Button type="primary" onClick={() => resetQueryParams()}>
                                            重置
                                        </Button>
                                    </Space>
                                </Form.Item>
                            </Col>
                            <Col span={4}>
                                <Flex gap="small" justify="flex-end">
                                    <Button type="primary" icon={<PlusOutlined />} onClick={() => {
                                        if (sysFormRef.current?.reset) {
                                            sysFormRef.current?.reset();
                                        }
                                        setUpdateSys(undefined)
                                        setOpenDrawStatus(true);
                                    }}>
                                        添加
                                    </Button>
                                </Flex>
                            </Col>
                        </Row>
                    </Form>
                </TableHeader>
                <TableContainer>
                    {isError ? (
                        <ErrorBox error={error as { message: string }} />
                    ) : (
                        <Table
                            rowSelection={{ type: 'checkbox' }}
                            pagination={paginationProps}
                            dataSource={dataSource?.list}
                            columns={columns}
                            loading={isLoading}
                            rowKey={(row) => row?.sysId}
                        />
                    )}
                </TableContainer>
                <SysForm
                    unitRef={unitTreeRef}
                    open={openSysDrawStatus}
                    sys={updateSys}
                    onCloseHandler={onCloseHandler}
                    onRef={sysFormRef}
                    refetch={refetch}
                />
            </BaseContiner>
        </RightContainer >
    </FlexContainer >
};

export default SysPage;
